package cn.woniu.ecommerceplatform.service.impl;

import cn.woniu.ecommerceplatform.entity.Goods;
import cn.woniu.ecommerceplatform.entity.Type;
import cn.woniu.ecommerceplatform.mapper.GoodsMapper;
import cn.woniu.ecommerceplatform.mapper.TypeMapper;
import cn.woniu.ecommerceplatform.service.CommonService;
import cn.woniu.ecommerceplatform.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author NCQ
 * @date 2023/1/6
 * 文件上传
 */
@Service
public class CommonServiceImpl implements CommonService {
    /**
     * 商品图片保存路径
     */
    @Value("${imgPath.path}")
    private String goodImgPath;

    @Autowired(required = false)
    private GoodsMapper goodsMapper;
    @Resource
    private TypeMapper typeMapper;
    /**
     * 商品图片上传方法
     * @param file 前端上传的文件
     * @return
     */
    @Override
    public ResponseResult<?> upload(MultipartFile file) {
        //File是个临时文件需要转存到具体路径才能永久保存
        String originalFilename = file.getOriginalFilename();
        //截取原始文件的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return new ResponseResult<>().notok("请选择jpg,jpeg,gif,png格式的图片");
        }
        //使用uuid和当前时间重新生成文件名
        Date date = new Date();
        long time = date.getTime();
        String fileName = time + UUID.randomUUID().toString().replace("-","") + "."+suffix;

        File dir =new File(goodImgPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String dirPath = dir.getAbsolutePath();
        try {
            file.transferTo(new File(dirPath+File.separator+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseResult<>().ok(fileName);
    }

    /**
     * 商品图片下载方法
     * @param name 文件名
     * @param response 返回请求
     * @return
     */
    @Override
    public void download(String name, HttpServletResponse response) {
        try {
            // 输入流，通过输入流读取文件内容
            File dir =new File(goodImgPath);
            if(!dir.exists()){
                dir.mkdirs();
            }
            String dirPath = dir.getAbsolutePath();
            FileInputStream fileInputStream = new FileInputStream(new File(dirPath +File.separator+ name));

            // 输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            // 输出的是图片，可以设置一下格式
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            // 输出结束后关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消上传
     * @param goods 商品信息
     * @return
     */
    @Override
    public ResponseResult<?> quit(Goods goods) {
        Goods goods1 = goodsMapper.queryGoodById(goods.getId());
        if(goods1!=null){
            if(!goods1.getGoodImg().equals(goods.getGoodImg())){
                if (deleteGoodsImg(goods))
                    return new ResponseResult<>().ok(null, "取消成功");
            }
        }else{
            if (deleteGoodsImg(goods))
                return new ResponseResult<>().ok(null, "取消成功");
        }
        return new ResponseResult<>().notok("没有更改图片");
    }

    @Override
    public ResponseResult<?> quitType(Type type) {
        Type type1 = typeMapper.selectById(type.getId());
        if (type1 != null){
            if (!type1.getTypeLogo().equals(type.getTypeLogo())){
                if (deleteTypeImg(type))
                    return new ResponseResult<>().ok(null,"取消成功");
            }
        } else {
            if (deleteTypeImg(type))
                return new ResponseResult<>().ok(null,"取消成功");
        }
        return new ResponseResult<>().notok("没有修改图片");
    }

    /**
     * 删除分类文件夹里的图片
     * @param type
     * @return
     */
    private boolean deleteTypeImg(Type type){
        String logo = type.getTypeLogo();
        String imgName = logo.substring(logo.lastIndexOf("/") + 1);
        File dir =new File(goodImgPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String dirPath = dir.getAbsolutePath();
        File file = new File(dirPath +File.separator+ imgName);
        if (file.exists()){
            file.delete();
            return true;
        }
        return false;
    }
    private boolean deleteGoodsImg(Goods goods) {
        String goodImg = goods.getGoodImg();
        String imgName = goodImg.substring(goodImg.lastIndexOf("/") + 1);
        File dir =new File(goodImgPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String dirPath = dir.getAbsolutePath();
        File file=new File(dirPath+File.separator+imgName);
        if(file.exists()){
            file.delete();
            return true;
        }
        return false;
    }
}
